<?php
namespace app\admin\controller;
use app\admin\model\Agent;
use think\Cache;
use think\Db;

/**
 * 商家管理
 * Class Member
 */
class AgentController extends BaseController {

    protected function _initialize() {
        parent::_initialize();
    }

    /**
     * 用户管理
     * @param string $keyword
     * @param int    $page
     * @return mixed
     */
    public function index($keyword = '', $ziduan = 'id', $param='add_time', $sort='desc') {
        $map = [];
		$order = 'a.'.$param. ' '.$sort;
		$this->assign('param', $param);
		$this->assign('sort', $sort);
        if ($keyword) {
            $map['a.'.$ziduan] = $keyword;
        }
		
        if (input('goodstype')) {
            $map['a.goodstype'] = input('goodstype');
        }
		$this->assign('ziduan', $ziduan);
        $member_list = db('agent')->alias('a')
					->join('goodstype b','a.goodstype = b.id','LEFT')
					->field('a.*,b.name as typename')
        			->where($map)->order($order)->paginate(15, false, get_query());
					
    	$type_list = db('goodstype')->select();
        $this->assign('type_list',$type_list);
        return $this->fetch('index', ['agent_list' => $member_list, 'keyword' => $keyword]);
    }
	
    /**
     * 商家二维码
     */
	public function ewm()
    {
    	$agent_info = db('agent')->where('id',input('agent_id'))->find();    	
    	$code_url="https://".$_SERVER['HTTP_HOST']."/index/jiangpin/lingqu?agent_id=".$agent_info['id'];
		
    	$agent_info['code_url'] = $code_url;    	
    	$this->assign('agent_info',$agent_info);	
    	return $this->fetch();
    }
	
    /**
     * 添加商家
     * @return mixed
     */
    public function add() {
    	$type_list = db('goodstype')->select();
        $this->assign('type_list',$type_list);
        return $this->fetch();
    }

    /**
     * 保存商家
     */
    public function save() {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Agent');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
				$data['add_time'] = now_time();
				 // 生成随机六位数，不足六位两边补零
    			$pwd = str_pad(mt_rand(0, 999999), 6, "0", STR_PAD_BOTH);
				$data['password'] = $pwd;
				$agent_model = new Agent();
                if ($agent_model->allowField(true)->save($data)) {
                    $this->success('添加成功',url('index'));
                } else {
                    $this->error('添加失败');
                }
            }
        }
    }

    /**
     * 编辑商家
     * @param $id
     * @return mixed
     */
    public function edit($id) {
    	$agent_model = new Agent();
        $agent = $agent_model->find($id);
				
    	$type_list = db('goodstype')->select();
        $this->assign('type_list',$type_list);
        return $this->fetch('edit', ['agent' => $agent]);
    }

    /**
     * 更新商家
     * @param $id
     */
    public function update($id) {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Agent');

            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
				$agent_model = new Agent();
                if ($agent_model->allowField(true)->save($data,['id'=>$id]) !== false) {
                    $this->success('更新成功',url('index'));
                } else {
                    $this->error('更新失败');
                }
            }
        }
    }
	
	//删除商家
	public function delete_item(){
		$res = del_data("agent",input("id"));
		if($res){
			 $this->success('删除成功',url("manage"));
		}else{
			 $this->success('删除失败');
		}
	}
	
	
	//商家赠送
	public function give()
    {
    	$this->assign('id',input('id'));
    	$data = db('agent')->field('id,givenum')->find(input('id'));
    	$this->assign('data',$data);

    	return $this->fetch();
    }
	
	//商家赠送
	public function givechange()
    {
    	if($_POST){
	        $parm['givenum'] = $_POST['give_num'];  
	        $result = db('agent')->where('id',$_POST['id'])->update($parm);
	        if($result){
				return json(['code'=>200,'msg'=>'操作成功']);
	        }else{
	       		return json(['code'=>402,'msg'=>'操作失败']);
	        }
        }
		return $this->fetch();
    }

    /**
     * 商家免费票二维码
     */
	public function zsewm()
    {
    	$agent_info = db('agent')->where('id',input('agent_id'))->find();    	
    	$code_url="https://".$_SERVER['HTTP_HOST']."/index/index/freeticket?agent_id=".$agent_info['id'];
		
    	$agent_info['code_url'] = $code_url;    	
    	$this->assign('agent_info',$agent_info);	
    	return $this->fetch();
    }
	
	 /**
     * 分享配置
     */
    public function sharesz() {
		if ($this->request->isPost()) {
            $ticket_config   = $this->request->post('share_config/a');
            $data['value'] = serialize($ticket_config);
            if (Db::name('system')->where('name', 'share_config')->update($data) !== false) {
                Cache::set('share_config', $ticket_config);
                $this->success('提交成功');
            } else {
                $this->error('提交失败');
            }
        }else{
        	if (Cache::has('')) {
	            $ticket_config = Cache::get('share_config');
	        } else {
	            $ticket_config = Db::name('system')->field('value')->where('name', 'share_config')->find();
	            $ticket_config = unserialize($ticket_config['value']);
	        }
        	return $this->fetch('sharesz', ['share_config' => $ticket_config]);
        }
    }
	
	//编辑地址
    function edit_address(){
    	if($_POST){
    		$data['longitude'] = input("lng");
			$data['latitude'] = input("lat");
			$data['address'] = input("address");
    		$res = db('agent')->where('id',input("agent_id"))->update($data);
			if($res){
				return json(["code"=>200,'msg'=>'修改成功']);
			}else{
				return json(["code"=>400,'msg'=>'修改失败']);
			}
    	}
		return $this->fetch();
    }
}
